<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="会员名称" prop="memberName">
        <el-input
          v-model="queryParams.memberName"
          placeholder="请输入会员名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderSn">
        <el-input
          v-model="queryParams.orderSn"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付时间" prop="payTime">
        <el-date-picker clearable
          v-model="queryParams.payTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择支付时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['huiyuan:records:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['huiyuan:records:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['huiyuan:records:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['huiyuan:records:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="会员名称" align="center" prop="memberName" />
      <el-table-column label="订单号" align="center" prop="orderSn" />
      <el-table-column label="充值金额" align="center" prop="rechargeAmount" />
      <el-table-column label="充值方式" align="center" prop="rechargeMethod" />
      <el-table-column label="支付状态" align="center" prop="payStatus" />
      <el-table-column label="充值时间" align="center" prop="rechargeTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.rechargeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" prop="payTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['huiyuan:records:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['huiyuan:records:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改充值记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会员ID" prop="member1Id">
          <el-input v-model="form.member1Id" placeholder="请输入会员ID" />
        </el-form-item>
        <el-form-item label="订单号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="充值金额" prop="rechargeAmount">
          <el-input v-model="form.rechargeAmount" placeholder="请输入充值金额" />
        </el-form-item>
        <el-form-item label="充值方式" prop="rechargeMethod">
          <el-input v-model="form.rechargeMethod" placeholder="请输入充值方式" />
        </el-form-item>
        <el-form-item label="充值状态" prop="payStatus">
          <el-select v-model="form.payStatus" placeholder="请选择充值状态">
            <el-option label="未付款" value="未付款" />
            <el-option label="已付款" value="已付款" />
          </el-select>
        </el-form-item>
        <el-form-item label="充值时间" prop="rechargeTime">
          <el-date-picker clearable
            v-model="form.rechargeTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择充值时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker clearable
            v-model="form.payTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Records">
import { listRecords, getRecords, delRecords, addRecords, updateRecords } from "@/api/huiyuan/records"
import {addFlow,getBalanceAfter} from "@/api/huiyuan/flow";

const { proxy } = getCurrentInstance()

const recordsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    member1Id: null,
    orderSn: null,
    payTime: null
  },
  rules: {
    member1Id: [
      { required: true, message: "会员ID不能为空", trigger: "blur" }
    ],
    orderSn: [
      { required: true, message: "订单号不能为空", trigger: "blur" }
    ],
    rechargeAmount: [
      { required: true, message: "充值金额不能为空", trigger: "blur" }
    ],
    payStatus: [
      { required: true, message: "支付状态不能为空", trigger: "change" }
    ],
    rechargeTime: [
      { required: true, message: "充值时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询充值记录列表 */
function getList() {
  loading.value = true
  listRecords(queryParams.value).then(response => {
    recordsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    member1Id: null,
    orderSn: null,
    rechargeAmount: null,
    rechargeMethod: null,
    payStatus: null,
    rechargeTime: null,
    payTime: null
  }
  proxy.resetForm("recordsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加充值记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRecords(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改充值记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRecords(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // 新增充值记录
        handleAddRecords()
      }
    }
  })
}

/** 处理新增充值记录 */
async function handleAddRecords() {
  try {
    // 先添加充值记录
    await addRecords(form.value)
    proxy.$modal.msgSuccess("充值记录新增成功")
    open.value = false
    getList()
    
    // 只有充值状态为"已付款"时才添加资金流水记录
    if (form.value.payStatus === '已付款') {
      await handleAddFlowRecord()
    } else {
      console.log("充值状态为未付款，不添加资金流水记录")
    }
  } catch (error) {
    proxy.$modal.msgError("充值记录新增失败：" + error.message)
  }
}

/** 处理添加资金流水记录 */
async function handleAddFlowRecord() {
  try {
    // 获取上一条记录的balanceAfter
    const response = await getBalanceAfter(form.value.member1Id)
    console.log("获取上一条记录响应：", response)
    
    let lastARecord = 0
    if (response.data && response.data !== null) {
      lastARecord = Number(response.data)
    }
    console.log("计算得到的lastARecord：", lastARecord)
    
    // 生成新的flowId
    const flowId = generateFlowId()
    
    // 构建资金流水数据
    const flowData = {
      flowId: flowId,
      memberId: form.value.member1Id,
      changeType: '余额充值',
      changeAmount: form.value.rechargeAmount,
      balanceAfter: lastARecord + Number(form.value.rechargeAmount),
      flowTime: form.value.payTime,
      description: `会员余额充值，充值单号为：${form.value.orderSn}`
    }
    // 添加资金流水记录
    console.log("准备添加资金流水记录，数据：", flowData)
    await addFlow(flowData)
    console.log("资金流水记录新增成功")
    proxy.$modal.msgSuccess("资金流水记录新增成功")
  } catch (error) {
    console.error("资金流水记录新增失败：", error)
    proxy.$modal.msgError("资金流水记录新增失败：" + error.message)
  }
}

/** 生成流水ID */
function generateFlowId() {
  // 从本地存储取最新序号，无则初始化为 0
  let latestNo = parseInt(localStorage.getItem('flowIdNo') || '0')
  // 生成新 flowId：ff_ + 6 位补零序号
  const flowId = `ff_${String(latestNo).padStart(6, '0')}`
  // 序号 +1 存回，下次用
  localStorage.setItem('flowIdNo', latestNo + 1)
  return flowId
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除充值记录编号为"' + _ids + '"的数据项？').then(function() {
    return delRecords(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('huiyuan/records/export', {
    ...queryParams.value
  }, `records_${new Date().getTime()}.xlsx`)
}

getList()
</script>
